<template>
  <div style="font-size: 20px; margin-left: 20%; margin-bottom: 20px">采购订单</div>
  <el-form label-width="auto" style="max-width: 50%">
    <!-- 循环渲染采购项 -->
    <div v-for="(item, index) in formDataList" :key="index">
      <el-form-item label="采购药品名称">
        <el-select
          v-model="item.medicineId"
          placeholder="请选择采购药品"
          filterable
          default-first-option
          clearable
        >
          <el-option
            v-for="medicine in medicines"
            :key="medicine.id"
            :label="medicine.label"
            :value="medicine.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="采购数量">
        <el-input v-model="item.quantity" placeholder="请输入采购数量" clearable />
      </el-form-item>
      <el-form-item label="采购单价">
        <el-input v-model="item.unitPrice" placeholder="请输入采购单价" clearable />
      </el-form-item>

      <el-form-item label="小计金额">
        <el-input v-model="item.subtotal" readonly clearable />
        <!-- 只在最后一项显示添加按钮 -->
        <el-button
          v-if="index === formDataList.length - 1"
          @click="addFormItem"
          style="margin-top: 8px"
        >
          添加新项
        </el-button>
      </el-form-item>
    </div>
    <el-form-item label="供应商名称">
      <el-input v-model="formData.supplier" placeholder="请输入供应商名称" clearable />
    </el-form-item>
    <!-- 总金额 -->
    <el-form-item label="总采购金额">
      <el-input :model-value="totalCost" readonly />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitButton" style="margin-left: 40%">提交订单</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, computed, onMounted, toRaw, watchEffect } from 'vue'
import myAxios from '../../axios/myAxios'
import { ElMessage } from 'element-plus'

// 采购项类型定义
interface PurchaseItem {
  detailId: number | string
  orderId: number | string
  medicineId: number | string
  medicineName: string
  quantity: number
  unitPrice: number
  subtotal: number
  supplier: string
  order_date: string
  total_cost: number
  status: string
  admin_id: string | number
}
const formData = reactive({
  supplier: '',
})
// 使用数组存储多个采购项
const formDataList = reactive<PurchaseItem[]>([
  {
    detailId: '',
    orderId: '',
    medicineId: '',
    medicineName: '',
    quantity: null,
    unitPrice: null,
    subtotal: null,
    supplier: '',
    order_date: '',
    total_cost: null,
    status: '',
    admin_id: '',
  },
])

// 添加新采购项
const addFormItem = () => {
  formDataList.push({
    detailId: '',
    orderId: '',
    medicineId: '',
    medicineName: '',
    quantity: null,
    unitPrice: null,
    subtotal: null,
    supplier: '',
    order_date: '',
    total_cost: null,
    status: '',
    admin_id: '',
  })
}
watchEffect(() => {
  formDataList.forEach((item) => {
    const quantity = item.quantity
    const unitPrice = item.unitPrice
    item.subtotal = quantity * unitPrice
  })
})
// 计算总金额
const totalCost = computed(() => {
  return formDataList.reduce((sum, item) => {
    return sum + (Number(item.subtotal) || 0)
  }, 0)
})

const submitButton = () => {
  myAxios
    .post('purchase/create', {
      supplier: formData.supplier,
      totalCost: totalCost.value,
      status: '待审核',
    })
    .then((res) => {
      if (res.data.code === 200) {
        myAxios
          .post(
            'purchase/detail/batch-create',
            toRaw(formDataList).map((item) => {
              return {
                orderId: res.data.data.id,
                medicineId: item.medicineId,
                quantity: item.quantity,
                unitPrice: item.unitPrice,
                subtotal: item.subtotal,
              }
            }),
          )
          .then(() => {
            ElMessage({
              message: '提交成功',
              type: 'success',
            })
          })
      }
    })
}

const medicines = reactive([])
onMounted(() => {
  myAxios.get('medicine/list').then((res) => {
    res.data.data.records.forEach((item) => {
      medicines.push({ id: item.id, label: item.name, value: item.id })
    })
  })
})
</script>
